/*
 * Copyright (c) 2014. kupat Corporation. All rights reserved.
 * see statement on http://www.kupat.cn.
 */

package com.kfgj.hkp.common.i18n;

import com.kfgj.hkp.common.logging.Logger;
import com.kfgj.hkp.common.logging.LoggerFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.MessageFormat;
import java.util.Properties;

/**
 * Created by liwensihan on 2015-7-31.
 *
 * @author liwensihan
 */
public class ConfigurationLoader {

    private Logger logger = LoggerFactory.getLogger(ConfigurationLoader.class);

    private String filePattern;

    private Properties config = new Properties();

    public ConfigurationLoader(String filePattern){
        this.filePattern = filePattern;
        try {
            //加载指定位置的properties文件
            PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            Resource[] resources = resolver.getResources("classpath*:"+filePattern);
            for (Resource resource : resources) {
                String path = resource.getURL().getPath();
                if (logger.isInfoEnabled()) {
                    logger.info("[Framework] add filePattern bundle: " + path);
                }
                //取得文件名
                Properties properties = new Properties();
                InputStream in = resource.getInputStream();

                BufferedReader bf = new BufferedReader(new InputStreamReader(in));
                try {
                    properties.load(bf);
                } finally {
                    in.close();
                }
                config.putAll(properties);
            }
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
    }

    public String getValue(String code){
        return config.getProperty(code, code);
    }

    public String getValue(String code,String... args){
        return MessageFormat.format(config.getProperty(code, code), args);
    }

}
